package org.jeecg.modules.wx.account.service;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.modules.wx.entity.WxAccount;
import org.jeecg.common.modules.wx.service.IWxAccountService;
import org.springframework.stereotype.Service;
import org.weixin4j.WeixinException;
import org.weixin4j.model.base.Token;
import org.weixin4j.model.js.Ticket;
import org.weixin4j.spring.WeixinTemplate;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author guoyh
 * @ClassName AdminWxAccountService
 * @Description
 * @since 2020/9/14 23:12
 **/
@Service
@Slf4j
public class AdminWxAccountService {
    @Resource
    private WeixinTemplate weixinTemplate;

    @Resource
    private IWxAccountService wxAccountService;

    public Result getAccessToken(String accountId){
        try {
            WxAccount wxAccount = wxAccountService.getByAccountId(accountId);
            if (Objects.isNull(wxAccount)){
                return Result.error("未获取到公众号信息");
            }
            Token token = weixinTemplate.getToken();
            return Result.ok(token);
        } catch (WeixinException e) {
            log.error("获取token异常",e);
            return Result.error("获取accessToken 异常");
        }
    }

    public Result getJsTicket(String accountId){
        try {
            WxAccount wxAccount = wxAccountService.getByAccountId(accountId);
            if (Objects.isNull(wxAccount)){
                return Result.error("未获取到公众号信息");
            }
            Ticket ticket = weixinTemplate.getJsApiTicket();
            return Result.ok(ticket);
        } catch (WeixinException e) {
            log.error("获取jsTicket异常",e);
            return Result.error("获取jsTicket异常");
        }
    }
}
